package com.imnjh.imagepicker.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.imnjh.imagepicker.CapturePhotoHelper;
import com.imnjh.imagepicker.R;
import com.imnjh.imagepicker.SImagePicker;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import static com.imnjh.imagepicker.activity.PhotoPickerActivity.EXTRA_RESULT_ORIGINAL;
import static com.imnjh.imagepicker.activity.PhotoPickerActivity.EXTRA_RESULT_SELECTION;


/**
 * Created by Martin on 2017/1/17.
 */

public class CaptureTempActivity extends BasePickerActivity {

    public static final String CAPTURE_URI = "capture_uri";
    public static final String CAPTURE_CROP = "is_crop";

    private CapturePhotoHelper capturePhotoHelper;

    private Uri uri;
    private boolean isCrop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        capturePhotoHelper = new CapturePhotoHelper(this);
        if (savedInstanceState == null) {
            uri = getIntent().getParcelableExtra(CAPTURE_URI);
            isCrop = getIntent().getBooleanExtra(CAPTURE_CROP, false);
            applyWritePermission();
        } else {
            uri = (Uri) savedInstanceState.get(CAPTURE_URI);
        }
        if (uri == null) {
            finishWith(Activity.RESULT_CANCELED);
        }

    }


    public void applyWritePermission() {

        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT >= 23) {
            int check = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED) {
                //调用相机
                capturePhotoHelper.capturePhoto(uri, isCrop);
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } else {
            capturePhotoHelper.capturePhoto(uri, isCrop);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            capturePhotoHelper.capturePhoto(uri, isCrop);
        } else {
            // 没有获取 到权限，从新请求，或者关闭app
            Toast.makeText(this, "需要存储权限", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(CAPTURE_URI, uri);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_capture_temp;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("CaptureTempActivity", "requestCode " + requestCode + " resultCode " + resultCode);
        if (resultCode == RESULT_OK && CapturePhotoHelper.photoFile!=null) {
            String path  = CapturePhotoHelper.photoFile.getAbsolutePath();
            Log.d("CaptureTempActivity", "requestCode   "+path+" "+new File(path).exists());
            if (requestCode == CaptureConfirmActivity.REQUEST_CODE_CONFIRM) {
                finishWith(RESULT_OK);
            } else if (requestCode == CapturePhotoHelper.CAPTURE_PHOTO_REQUEST_CODE) {
//                CaptureConfirmActivity.launch(this, uri);
                Intent intent = new Intent();
                intent.putExtra(CropImageActivity.RESULT_PATH, path);
                setResult(RESULT_OK, intent);
                finish();
            } else if (requestCode == CapturePhotoHelper.CROP_CAPTURE_PHOTO_REQUEST_CODE) {
                // 启动剪切图片
                CropImageActivity.startImageCrop(this, path,
                        PhotoPickerActivity.REQUEST_CODE_CROP_IMAGE,
                        SImagePicker.getPickerConfig().getAvatarPath()
                );
            } else if (requestCode == PhotoPickerActivity.REQUEST_CODE_CROP_IMAGE) {
                if (data != null) {
                    // 剪切完的图片
                    String paths = data.getStringExtra(CropImageActivity.RESULT_PATH);
                    ArrayList<String> result = new ArrayList<>();
                    if(!TextUtils.isEmpty(paths)) {
                        result.add(paths);
                        Intent intent = new Intent();
                        intent.putStringArrayListExtra(EXTRA_RESULT_SELECTION, result);
                        intent.putExtra(EXTRA_RESULT_ORIGINAL, true);
                        setResult(resultCode, intent);
                    }
                }
                finish();
            }
        } else if (resultCode == RESULT_CANCELED) {
            finishWith(RESULT_CANCELED);
        } else if (resultCode == CaptureConfirmActivity.RESULT_CODE_RETRY) {
            File photoFile = new File(uri.getPath());
            if (photoFile.exists()) {
                photoFile.delete();
            }
            try {
                photoFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            capturePhotoHelper.capturePhoto(uri, isCrop);
        } else {
            Log.d("elseCaptureTempActivity", "requestCode" + uri.getPath());
        }
    }

    private void finishWith(int resultCode) {
        setResult(resultCode);
        finish();
    }
}
